package com.youpingou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youpingou.domain.Category;
import com.youpingou.mapper.CategoryMapper;
import com.youpingou.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> findAll() {

        //1 条件
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("parent_id");

        //2 查询所有
        List<Category> allList = baseMapper.selectList(queryWrapper);

        //1 查找一级分类
        List<Category> list1 = this.findCategoryByParentId(0,allList);
        //2 遍历一级分类，查找二级分类
        for(Category c1:list1){
            //3 查找二级分类
            List<Category> list2 = this.findCategoryByParentId(c1.getId(),allList);
            // 4 将二级分类给一级分类
            c1.setChildren(list2);
            //5 遍历二级分类，查找三级分类
            for(Category c2:list2){
                //6 查找三级分类
                List<Category> list3 = this.findCategoryByParentId(c2.getId(),allList);
                //7 将三级分类给二级分类
                c2.setChildren(list3);
            }
        }
        // 8 返回结果
        return list1;
    }


    /**
     * 当你查询完之后，数据是放在内存中的，所以此方法是在内存中处理数据
     * @param parentId
     * @param allList
     * @return
     */
    public List<Category> findCategoryByParentId(Integer parentId,List<Category> allList){
        // 定义子集合
        ArrayList<Category> childrenList = new ArrayList<>();
        // 遍历总集合，根据parentId查找出子类
        for(Category c:allList){
            //判断parentId
            if(c.getParentId()!=null&&!c.getParentId().equals("")&&c.getParentId().equals(parentId)){
                //添加至子集合
                childrenList.add(c);
            }
        }
        return childrenList;
    }
}